package com.study.zzedu.ui.errorset;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;

import com.study.zzedu.R;
import com.study.zzedu.base.BaseMvpActivity;
import com.study.zzedu.base.BaseView;
import com.study.zzedu.utils.Base64Utils;
import com.study.zzedu.utils.ToastUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ErrorSetActivity extends BaseMvpActivity<BaseView, ErrorSetPresenter> implements BaseView {

    private RelativeLayout btnBack;
    private static final String HTTP = "http://";
    private static final String HTTPS = "https://";
    String myURL = "file:///android_asset/index.html#/index/mistakes";
    private WebView mWebView;
    @Override
    protected int getLayoutID() {
        return R.layout.activity_error_set_info;
    }

    @Override
    protected ErrorSetPresenter createPresenter() {
        return new ErrorSetPresenter();
    }

    @Override
    protected BaseView createView() {
        return this;
    }
    @Override
    protected void initView() {
        btnBack = findViewById(R.id.rl_back);
        mWebView = findViewById(R.id.webView1);
        initWeb();
    }
    private void initWeb() {
        // 重写 WebViewClient
        mWebView.setWebViewClient(new MkWebViewClient());
        // 重写 WebChromeClient
        mWebView.setWebChromeClient(new MkWebChromeClient());

        WebSettings settings = mWebView.getSettings();
        // 启用 js 功能
        settings.setJavaScriptEnabled(true);
        mWebView.addJavascriptInterface(new AndroidGotData(), "AndroidGotData");
        // 设置浏览器 UserAgent
        settings.setUserAgentString(settings.getUserAgentString() + " mkBrowser/" + getVerName(this));

        // 将图片调整到适合 WebView 的大小
        settings.setUseWideViewPort(true);
        // 缩放至屏幕的大小
        settings.setLoadWithOverviewMode(true);

        // 支持缩放，默认为true。是下面那个的前提。
        settings.setSupportZoom(true);
        // 设置内置的缩放控件。若为false，则该 WebView 不可缩放
        settings.setBuiltInZoomControls(true);
        // 隐藏原生的缩放控件
        settings.setDisplayZoomControls(false);

        // 缓存
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        // 设置可以访问文件
        settings.setAllowFileAccess(true);
        // 支持通过JS打开新窗口
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        // 支持自动加载图片
        settings.setLoadsImagesAutomatically(true);
        // 设置默认编码格式
        settings.setDefaultTextEncodingName("utf-8");
        // 本地存储
        settings.setDomStorageEnabled(true);
        settings.setPluginState(WebSettings.PluginState.ON);

        // 资源混合模式
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        try {
            if (Build.VERSION.SDK_INT >= 16) {
                Class<?> clazz = mWebView.getSettings().getClass();
                Method method = clazz.getMethod(
                        "setAllowUniversalAccessFromFileURLs", boolean.class);//利用反射机制去修改设置对象
                if (method != null) {
                    method.invoke(mWebView.getSettings(), true);//修改设置
                }
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        // 加载首页
        mWebView.loadUrl(myURL);
    }
    @Override
    protected void initData() {
        getPresenter().getErrorSetList(ErrorSetActivity.this);
    }

    @Override
    protected void initListener() {
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    public void getData(String data) {
        //ToastUtil.showShortToast("获得异动List");
        try {
            JSONObject jObject = new JSONObject(data);
            JSONArray jArray = jObject.getJSONArray("data");

            final String jsString = "javascript:SET_TEST_DATA('"+ Base64Utils.encode(jArray.toString())+"')";

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mWebView.evaluateJavascript(jsString, new ValueCallback<String>() {
                        @Override
                        public void onReceiveValue(String s) {
                            //将button显示的文字改成JS返回的字符串
                            //buttonLeft.setText(s);
                        }
                    });
                }
            },200);

        } catch (Exception e) {
            e.toString();
        }
    }

    @Override
    public void showError(String error) {
        if (null != error && !TextUtils.isEmpty(error)) {
            ToastUtil.showShortToast(error);
        }
    }

    /**
     * 重写 WebViewClient
     */
    private class MkWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // 设置在webView点击打开的新网页在当前界面显示,而不跳转到新的浏览器中

            if (url == null) {
                // 返回true自己处理，返回false不处理
                return true;
            }

            // 正常的内容，打开
            if (url.startsWith(HTTP) || url.startsWith(HTTPS)) {
                view.loadUrl(url);
                return true;
            }

            // 调用第三方应用，防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
            try {
                // TODO:弹窗提示用户，允许后再调用
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
                return true;
            } catch (Exception e) {
                return true;
            }
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            // 网页开始加载，显示进度条

        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }
    }


    /**
     * 重写 WebChromeClient
     */
    private class MkWebChromeClient extends WebChromeClient {
        private final static int WEB_PROGRESS_MAX = 100;

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);

        }

        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
            super.onReceivedIcon(view, icon);

        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);

        }
    }
    /**
     * 获取版本号名称
     *
     * @param context 上下文
     * @return 当前版本名称
     */
    private static String getVerName(Context context) {
        String verName = "unKnow";
        try {
            verName = context.getPackageManager().
                    getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }

    // 继承自Object类
    public class AndroidGotData extends Object {

        // 定义JS需要调用的方法
        // 被JS调用的方法必须加入@JavascriptInterface注解
        @JavascriptInterface
        public void getData(String msg) {

            ToastUtil.showLongToast(""+msg);
        }
    }
}